package com.example.questionnaire.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.questionnaire.dao.*;
import com.example.questionnaire.pojo.DAO.UserAnswerDataEncapsulationDAO;
import com.example.questionnaire.pojo.DAO.UserAnswerLimitValidationDAO;
import com.example.questionnaire.pojo.DO.*;
import com.example.questionnaire.service.UserAnswerService;
import com.example.questionnaire.util.CommonUtil;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;

import static com.example.questionnaire.util.CommonUtil.CompareTheCurrentDates;

@Service
public class UserAnswerServiceImpl implements UserAnswerService {


    @Autowired
    private QuestionnaireDataMapper questionnaireDataMapper;

    @Autowired
    private ResultMapper resultMapper;

    @Autowired
    private AllQuestionMapper allQuestionMapper;

    @Autowired
    private OptionsMapper optionsMapper;

    @Autowired
    private QuestionnaireMapper questionnaireMapper;

    @Autowired
    private ScoreQuestionMapper scoreQuestionMapper;

    @Autowired
    private EvaluateQuestionMapper evaluateQuestionMapper;

    @Override
    public boolean saveUserAnswerData(String formid, String answerSource, String ip, String phone, String openid, String result, int score) {
        String resultId = String.valueOf((CommonUtil.getRandomId()));

        QuestionnaireData questionnaireData = new QuestionnaireData();
        questionnaireData.setFormid(formid);
        questionnaireData.setAnswerSource(answerSource);
        questionnaireData.setIp(ip);
        questionnaireData.setPhone(phone);
        questionnaireData.setOpenid(openid);
        questionnaireData.setResultId(resultId);
        questionnaireData.setScore(score);
        questionnaireDataMapper.insert(questionnaireData);


        // JSON字符串转换成JSON大数组
        JSONArray jsonBigArray = JSON.parseArray(result);

        for (int i = 0; i < jsonBigArray.size(); i++) {
            JSONObject jsonObject = jsonBigArray.getJSONObject(i);

            Result result1 = new Result();
            result1.setResultId(resultId);
            result1.setSubjectId(String.valueOf(jsonObject.get("subjectId")));
            result1.setOptionsName(String.valueOf(jsonObject.get("value")));

            resultMapper.insert(result1);
        }

//        UpdateWrapper<Questionnaire> wrapper = new UpdateWrapper<>();
//        wrapper.eq("formid", formid)
//                .setSql("'answer_number' = 'answer_number' + 1");
//        questionnaireMapper.update(null,wrapper);有神秘力量的方法（会报错，而且报错在很奇怪的地方（报错在请求头相关问题那））

        //让答卷数量增长
        QueryWrapper<Questionnaire> wrapper = new QueryWrapper<>();
        wrapper.eq("formid", formid);
        Questionnaire questionnaire = questionnaireMapper.selectOne(wrapper);
        int answerNumber = questionnaire.getAnswerNumber();
        answerNumber ++;
        UpdateWrapper<Questionnaire> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("formid", formid)
                .set("answer_number", answerNumber);
        if (questionnaireMapper.update(null, updateWrapper) < 1) {
            throw new RuntimeException("插入失败");
        }

        return true;
    }

    @Override
    public List<UserAnswerDataEncapsulationDAO> statistics(String formid) throws IOException {
        List<UserAnswerDataEncapsulationDAO> result = new ArrayList<>();
        QueryWrapper<AllQuestion> wrapper = new QueryWrapper<>();
        wrapper.eq("formid", formid)
                .orderByAsc("subject_num")
                .select("subject_num", "subject_id", "question_type", "title");
        List<AllQuestion> subjectNum = allQuestionMapper.selectList(wrapper);
        for (AllQuestion i : subjectNum) {
            UserAnswerDataEncapsulationDAO userAnswerDataEncapsulationDAO = new UserAnswerDataEncapsulationDAO();
            userAnswerDataEncapsulationDAO.setSubjectId(i.getSubjectId());
            userAnswerDataEncapsulationDAO.setTitle(i.getTitle());
            List value = new ArrayList<>();
            QueryWrapper<Result> wrapper2 = new QueryWrapper<>();
            wrapper2.eq("subject_id", i.getSubjectId())
                    .select("options_name");
            List<Result> optionName = resultMapper.selectList(wrapper2);
            if(optionName.size() == 0){
                return result;
            }
            // List optionName = resultMapper.selectOptionName(String.valueOf(i.getSubjectId()));
            if (i.getQuestionType() == 3) {
                List<String> list = new ArrayList<>();
                Map<String, Object> temp = new HashMap<>();
                for (Result klkl : optionName) {
                    String tempName = klkl.getOptionsName().replace("[", "").replace("]", "").replace("\"", "");
                    temp.put("content", tempName);
                    String s = JSONObject.toJSONString(temp);
                    list.add(s);
                }
                userAnswerDataEncapsulationDAO.setValue(list);
            }
            if (i.getQuestionType() == 4) {
                Map<String, String> temp = new HashMap<>();
                for(int blb = 1;blb < scoreQuestionMapper.selectByScoreSettings(i.getSubjectId())+1;blb++){
                    temp.put("optionName", String.valueOf(blb));
                    int count = 0;
                    String wmk = "[\"" + blb + "\"]";
                    for (Result klkl : optionName) {
                        if (wmk.equals(klkl.getOptionsName())) {
                            count++;
                        }
                    }
                    if (optionName.size()>0){
                        BigDecimal bd = new BigDecimal(count * 100 / optionName.size());
                        bd = bd.setScale(2, RoundingMode.HALF_UP);
                        temp.put("num", bd.toString() + "%");
                        String s = JSONObject.toJSONString(temp);
                        value.add(s);

                    }else{
                        temp.put("num", "0%");
                        String s = JSONObject.toJSONString(temp);
                        value.add(s);
                    }
                }
                userAnswerDataEncapsulationDAO.setValue(value);
            }
            if (i.getQuestionType() == 5) {
                Map<String, Object> temp = new HashMap<>();
                // JSON字符串转换成JSON大数组
                JSONArray jsonBigArray = JSON.parseArray(evaluateQuestionMapper.selectByEvaluation(i.getSubjectId()));
                for (int blb = 0; blb < jsonBigArray.size(); blb ++){
                    JSONObject jsonObject = jsonBigArray.getJSONObject(blb);
//                    String wmk = "[\"" + jsonObject.get("content") + "\"]";

                    temp.put("optionName",jsonObject.get("content"));
                    int count = 0;
                    String wmk = "[\"" + jsonObject.get("content") + "\"]";
                    for (Result klkl : optionName) {
                        if (wmk.equals(klkl.getOptionsName())) {
                            count++;
                        }
                    }
                    if (optionName.size()>0){
                        BigDecimal bd = new BigDecimal(count * 100 / optionName.size());
                        bd = bd.setScale(2, RoundingMode.HALF_UP);
                        temp.put("num", bd.toString() + "%");
                        String s = JSONObject.toJSONString(temp);
                        value.add(s);

                    }else{
                        temp.put("num", "0%");
                        String s = JSONObject.toJSONString(temp);
                        value.add(s);
                    }
//                    List<String> list = objectMapper.readValue(String.valueOf(jsonObject.get("content")), new TypeReference<List<String>>() {});
//                    for(String list1 : list){
//
//                    }
                }
                userAnswerDataEncapsulationDAO.setValue(value);
            }
            else {
                QueryWrapper<Options> wrapper1 = new QueryWrapper<>();
                wrapper1.eq("subject_id", i.getSubjectId())
//                        .orderByAsc("create_time")
                        .orderByAsc("options_type")
                        .select("options_content");
                List<Options> optionContent = optionsMapper.selectList(wrapper1);

                for (Options j : optionContent) {
                    Map<String, Object> temp = new HashMap<>();
                    temp.put("optionName", j.getOptionsContent());
                    int count = 0;
                    if (i.getQuestionType() == 1) {
                        String wmk = j.getOptionsContent();
                        wmk = "[\"" + wmk + "\"]";
                        for (Result k : optionName) {//找出选此选项的个数
                            if (wmk.equals(k.getOptionsName())) {
                                count++;
                            }
                        }
                    }
                    if (i.getQuestionType() == 2) {
                        for (Result k : optionName) {//找出选此选项的个数
                            ObjectMapper objectMapper = new ObjectMapper();
                            List<String> list = objectMapper.readValue(String.valueOf(k.getOptionsName()), new TypeReference<List<String>>() {
                            });
                            for (String list1 : list) {
                                if (j.getOptionsContent().equals(list1)) {
                                    count++;
                                }
                            }
                        }
                    }
                    if (optionName.size()>0){
                        BigDecimal bd = new BigDecimal(count * 100 / optionName.size());
                        bd = bd.setScale(2, RoundingMode.HALF_UP);
                        temp.put("num", bd.toString() + "%");
                        String s = JSONObject.toJSONString(temp);
                        value.add(s);

                    }else{
                        temp.put("num", "0%");
                        String s = JSONObject.toJSONString(temp);
                        value.add(s);
                    }
                }
                userAnswerDataEncapsulationDAO.setValue(value);
            }
            result.add(userAnswerDataEncapsulationDAO);
        }
        return result;
    }

    @Override
    public Object limitValidation(String formid, String ip, String phone, String openid,int type) throws ParseException {
        List<Object> result = new ArrayList<>();
        QueryWrapper<QuestionnaireData> wrapper = new QueryWrapper<>();
        wrapper.eq("formid", formid)
                .select("ip","phone","openid","create_time");
        List<QuestionnaireData> dataList = questionnaireDataMapper.selectList(wrapper);
        int ipNum = 0;
        int phoneNum = 0;
        int openidNum = 0;
        int theDayAnswer = 0;
        for (QuestionnaireData i : dataList) {
            if(type == 0){
                if(i.getIp().equals(ip)){
                    ipNum++;
                }
                if(i.getPhone().equals(phone)){
                    phoneNum++;
                }
                if(i.getOpenid().equals(openid)){
                    openidNum++;
                }
            }else {
                if(i.getIp().equals(ip) && CompareTheCurrentDates(i.getCreateTime())){
                    ipNum++;
                }
                if(i.getPhone().equals(phone) && CompareTheCurrentDates(i.getCreateTime())){
                    phoneNum++;
                }
                if(i.getOpenid().equals(openid) && CompareTheCurrentDates(i.getCreateTime())){
                    openidNum++;
                }
            }if(i.getOpenid().equals(openid) || i.getPhone().equals(phone) || i.getIp().equals(ip)){
                if (type == 1 && CompareTheCurrentDates(i.getCreateTime())){
                    theDayAnswer ++;
                }
            }

        }
        int sum = dataList.size();
        UserAnswerLimitValidationDAO userAnswerLimitValidationDAO = new UserAnswerLimitValidationDAO();
        userAnswerLimitValidationDAO.setIpNum(ipNum);
        userAnswerLimitValidationDAO.setPhoneNum(phoneNum);
        userAnswerLimitValidationDAO.setOpenidNum(openidNum);
        userAnswerLimitValidationDAO.setSum(sum);
        userAnswerLimitValidationDAO.setTheDayAnswer(theDayAnswer);

        result.add(userAnswerLimitValidationDAO);

        return result;
    }

    @Override
    public List<Object> getStatement(String formid){
        List<String> resultIdSet1 = questionnaireDataMapper.getResultId(formid);
        List<Object> resultIdSet = new CopyOnWriteArrayList<>();
        for(String tempResultId : resultIdSet1) {
            Map<String, Object> tempResult = new HashMap<>();
            tempResult.put("fillInTheTime", questionnaireDataMapper.getFillInTheTime(tempResultId));
            tempResult.put("ip", questionnaireDataMapper.getIp(tempResultId));
            tempResult.put("answerSource", questionnaireDataMapper.getAnswerSource(tempResultId));
            List<String> optionArray1 = allQuestionMapper.selectSubjectId(formid);
            List<Object> optionArray = new CopyOnWriteArrayList<>();
            for (String tempSubjectId : optionArray1) {
                Map<String, Object> elements = new HashMap<>();
                elements.put("title",allQuestionMapper.selectTitle(tempSubjectId));
                elements.put("content", resultMapper.selectContent(String.valueOf(tempResult.get("fillInTheTime")), tempResultId, tempSubjectId));
                optionArray.add(elements);
            }
            tempResult.put("optionArray", optionArray);
            System.out.println(tempResult.get("optionArray"));
            resultIdSet.add(tempResult);
        }
        System.out.println(resultIdSet);
        return resultIdSet;
    }
}
